import {ANALYZERS, FIELD_TYPES, FieldItemProps, MappingField} from "@/components/IndexMapping/types";
import {useState} from '@/hooks';
import {Button, Card, Checkbox, Col, Form, FormItem, Input, Row, Select} from 'tdesign-vue-next';
import {AddIcon, ChevronDownIcon, ChevronRightIcon, DeleteIcon} from 'tdesign-icons-vue-next';


export function FieldItem({field, onUpdate, onDelete, level = 0}: FieldItemProps) {
  const [expanded, setExpanded] = useState(true)
  const [showAdvanced, setShowAdvanced] = useState(false)

  const addSubField = () => {
    const newSubField: MappingField = {
      id: `subfield-${Date.now()}`,
      name: "",
      type: "keyword",
    }
    onUpdate(field.id, {
      fields: [...(field.fields || []), newSubField],
    })
  }

  const addProperty = () => {
    const newProperty: MappingField = {
      id: `property-${Date.now()}`,
      name: "",
      type: "text",
      index: true,
    }
    onUpdate(field.id, {
      properties: [...(field.properties || []), newProperty],
    })
  }

  const updateSubField = (subFieldId: string, updates: Partial<MappingField>) => {
    const updatedFields = (field.fields || []).map((sf) => (sf.id === subFieldId ? {...sf, ...updates} : sf))
    onUpdate(field.id, {fields: updatedFields})
  }

  const deleteSubField = (subFieldId: string) => {
    const updatedFields = (field.fields || []).filter((sf) => sf.id !== subFieldId)
    onUpdate(field.id, {fields: updatedFields})
  }

  const updateProperty = (propId: string, updates: Partial<MappingField>) => {
    const updatedProperties = (field.properties || []).map((prop) =>
      prop.id === propId ? {...prop, ...updates} : prop,
    )
    onUpdate(field.id, {properties: updatedProperties})
  }

  const deleteProperty = (propId: string) => {
    const updatedProperties = (field.properties || []).filter((prop) => prop.id !== propId)
    onUpdate(field.id, {properties: updatedProperties})
  }

  const isComplexType = field.type === "object" || field.type === "nested"

  return (
    <Card class={level > 0 ? "ml-8" : ""}>
      <div class="pt-6 space-y-4">
        <div class="flex items-start gap-3">
          {(isComplexType || (field.fields && field.fields.length > 0)) && (
            <Button variant="outline" shape={'square'} class="h-8 w-8 shrink-0"
                    onClick={() => setExpanded(!expanded.value)}>
              {expanded.value ? <ChevronDownIcon/> : <ChevronRightIcon/>}
            </Button>
          )}
          <Row gutter={16}>
            <Col span={4}>
              <FormItem label={'字段名称'} labelAlign={'top'}>
                <Input
                  value={field.name}
                  onChange={(v) => onUpdate(field.id, {name: `${v}`})}
                  placeholder="field_name"
                />
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem label={'字段类型'} labelAlign={'top'}>
                <Select value={field.type} onChange={(value) => onUpdate(field.id, {type: `${value}`})}
                        options={FIELD_TYPES}/>
              </FormItem>
            </Col>
            <Col span={4}>
              <Button
                variant="outline"
                shape={'square'}
                onClick={() => onDelete(field.id)}
              >
                <DeleteIcon class="h-4 w-4"/>
              </Button>
            </Col>
          </Row>
        </div>

        {!isComplexType && (
          <>
            <div class="flex items-center justify-between">
              <Button variant="text" onClick={() => setShowAdvanced(!showAdvanced.value)}>
                {showAdvanced.value ? "隐藏" : "显示"}高级选项
              </Button>
            </div>

            {showAdvanced.value && (
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2 border-t">
                <Form>
                  <FormItem>
                    <Checkbox checked={field.index ?? true}
                              onChange={v => onUpdate(field.id, {index: v})}>索引</Checkbox>
                  </FormItem>
                  <FormItem>
                    <Checkbox checked={field.store ?? true}
                              onChange={v => onUpdate(field.id, {store: v})}>存储</Checkbox>
                  </FormItem>
                  <FormItem label={'分析器'}>
                    {field.type === "text" && (<Select
                      value={field.analyzer || "standard"}
                      onChange={(value) => onUpdate(field.id, {analyzer: `${value}`})}
                      options={ANALYZERS}
                    />)}
                  </FormItem>
                </Form>
              </div>
            )}

            {field.type === "text" && (
              <div class="pt-2 border-t">
                <div class="flex items-center justify-between mb-3">
                  <label>多字段 (Multi-fields)</label>
                  <Button variant="outline" onClick={addSubField}>
                    <AddIcon/>
                    添加
                  </Button>
                </div>
                {field.fields && field.fields.length > 0 && (
                  <div class="space-y-2">
                    {field.fields.map((subField) => (
                      <div key={subField.id} class="flex items-center gap-2 p-3 bg-muted rounded-lg">
                        <Input
                          value={subField.name}
                          onChange={(v) => updateSubField(subField.id, {name: `${v}`})}
                          placeholder="字段名称"
                          class="flex-1"
                        />
                        <Select
                          value={subField.type}
                          options={[{
                            label: 'keyword',
                            value: 'keyword',
                          }, {
                            label: 'text',
                            value: 'text',
                          }]}
                          onChange={(value) => updateSubField(subField.id, {type: `${value}`})}
                        />
                        <Button
                          variant="outline"
                          shape="square"
                          class="h-8 w-8 text-destructive"
                          onClick={() => deleteSubField(subField.id)}
                        >{{
                          icon: <AddIcon/>,
                          default: () => <span>添加</span>
                        }}
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </>
        )}

        {isComplexType && expanded.value && (
          <div class="pt-2 border-t space-y-3">
            <div class="flex items-center justify-between">
              <label>属性</label>
              <Button variant="outline" onClick={addProperty}>
                <AddIcon/>
                添加属性
              </Button>
            </div>
            {field.properties && field.properties.length > 0 && (
              <div class="space-y-3">
                {field.properties.map((prop) => (
                  <FieldItem
                    key={prop.id}
                    field={prop}
                    onUpdate={updateProperty}
                    onDelete={deleteProperty}
                    level={level + 1}
                  />
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </Card>
  )
}
